/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package FileOverNet;

import Echo.*;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.StyledEditorKit;

public class FileServer extends Thread {

    Socket clientSocket = null;
    OutputStream clientOutputStream = null;
    BufferedReader stdIn = null;

    public FileServer(Socket clientSocket) {

        this.clientSocket = clientSocket;

    }

    @Override
    public void run() {

        FileOutputStream fileOut = null;
        InputStream clientInStream = null;

        stdIn = new BufferedReader(new InputStreamReader(System.in));


        try {
            clientOutputStream = clientSocket.getOutputStream();
        } catch (IOException ex) {
            System.out.println("Couldn't get client output stream");
            //closeAllStreams();
            return;
        }

        PrintWriter clientOutputPrinter = new PrintWriter(clientOutputStream, true);


        while (true) {

            try {
                clientInStream = clientSocket.getInputStream();
            } catch (IOException ex) {
                System.out.println("Couldn't get client output stream");
                return;
            }

            //try {
            System.out.println("Enter command:");
            String userCommand = "";

            try {
                userCommand = stdIn.readLine().toLowerCase();
            } catch (IOException ex) {
                //closeAllStreams();
                return;
            }

            if (userCommand.equals("")) {
                continue;
            }

            switch (userCommand) {
                case "copyfile":

                    System.out.println("Enter file name you want copy:");
                    String fileNameSource;

                    try {
                        fileNameSource = stdIn.readLine();
                    } catch (IOException ex) {
                        closeStream(stdIn);
                        return;
                    }

                    System.out.println("Enter new file name:");
                    String fileNameDest;

                    try {
                        fileNameDest = stdIn.readLine();
                    } catch (IOException ex) {
                        //closeAllStreams();
                        return;
                    }

                    //отправляем запрос клиенту на файл, который хотим получить
                    PrintWriter outPrint;

                    try {
                        outPrint = new PrintWriter(clientSocket.getOutputStream(), true);
                    } catch (IOException ex) {
                        //closeAllStreams();
                        return;
                    }

                    outPrint.println("getFile");
                    outPrint.println(fileNameSource);

                    BufferedReader inReader = new BufferedReader(
                            new InputStreamReader(
                            clientInStream));

                    try {
                        //FILE READING
                        fileOut = new FileOutputStream(fileNameDest + ".mp3");
                    } catch (FileNotFoundException ex) {
                        System.out.println("Не смог открыть файл для записи");
                        continue;
                    }

                    int read = 0;
                    byte[] bytes = new byte[1024 * 1024];


                    try {
                        while ((read = clientInStream.read(bytes)) != -1) {
                            fileOut.write(bytes, 0, read);
                        }
                        fileOut.flush();
                    } catch (IOException ex) {
                        System.out.println("Чтение не удачно!");
                        return;
                    }

                    closeStream(fileOut);

                    System.out.println("Копирование завершено!");


                    break;

                case "exit":
                case "quit":    
                    //closeStream(clientSocket);
                    //closeStream(clientInStream);
            }

        }


    }

    public void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
            }
        }
    }

    public void closeAllStreams() {
        closeStream(clientOutputStream);
        closeStream(clientSocket);
        closeStream(stdIn);
    }

    public static void main(String[] args) throws IOException {



        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        Boolean listening = true;

        while (listening) {
            new FileServer(serverSocket.accept()).start();
        }

        serverSocket.close();





//        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
//        BufferedReader in = new BufferedReader(
//                new InputStreamReader(
//                clientSocket.getInputStream()));
//        String inputLine, outputLine;
// 
//        while ((inputLine = in.readLine()) != null) {
//             System.out.println(inputLine);
//             //out.println(outputLine);
//             if (inputLine.equals("quit"))
//                break;
//        }




    }
}
